using StudyCompanion.Core.Enum;
using StudyCompanion.Core.Repository;
using StudyCompanion.Core.Services;
using StudyCompanion.Entity.User;
using StudyCompanion.IServices;

namespace StudyCompanion.Services;

/// <summary>
///     钱包日志服务
/// </summary>
public class WalletLogService : BaseService, IWalletLogService
{
    private readonly BaseRepository<Users> _userRepository;
    private readonly BaseRepository<UseWalletLogEntity> _walletLogRepository;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="userRepository"></param>
    /// <param name="walletLogRepository"></param>
    public WalletLogService(BaseRepository<Users> userRepository,
        BaseRepository<UseWalletLogEntity> walletLogRepository)
    {
        _userRepository = userRepository;
        _walletLogRepository = walletLogRepository;
    }

    /// <summary>
    ///     写入钱包日志(状态成功)
    /// </summary>
    /// <param name="userId">用户ID</param>
    /// <param name="actionEnum">钱包操作（枚举）</param>
    /// <param name="typeEnum">操作类型（枚举）</param>
    /// <param name="changeCount">变化数量</param>
    /// <param name="orderId">关联订单ID</param>
    /// <param name="describe">描述</param>
    /// <param name="tableId">其他关联数据ID</param>
    public void WriteWalletLog(long userId, WalletActionEnum actionEnum,
        WalletTypeEnum typeEnum, decimal changeCount, long? orderId, string? describe, long? tableId)
    {
        var userInfo = _userRepository.Where(x => x.Id == userId).First();
        var useWalletLog = new UseWalletLogEntity
        {
            UserId = userId,
            OrderId = orderId,
            Action = (int)actionEnum,
            State = (int)WalletStateEnum.Succeed,
            Type = (int)typeEnum,
            ChangeCount = changeCount,
            ChangeFrontCount = userInfo.WalletBalance,
            Describe = describe,
            TableId = tableId
        };
        if (typeEnum == WalletTypeEnum.Add)
        {
            useWalletLog.ChangeLaterCount = userInfo.WalletBalance + changeCount;
            userInfo.WalletBalance += changeCount;
            userInfo.SumIncome += changeCount;
        }
        else
        {
            useWalletLog.ChangeLaterCount = userInfo.WalletBalance - changeCount;
            userInfo.WalletBalance -= changeCount;
        }

        _walletLogRepository.Insert(useWalletLog);
        _walletLogRepository.Change<Users>().Update(userInfo);
    }
}